﻿using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Windows;
using System.Globalization;
using Newtonsoft.Json;

namespace DataBoundApp1
{
    public class Json
    {
        public Json()
        {
            m_root = null;
        }
        public menuRoot m_root;


        // Deserializes the json string given as parameter
        // returns an object that is in the Juvenes menu form
        public menuRoot Deserialize(string json)
        {
            m_root = JsonConvert.DeserializeObject<menuRoot>(json);
            
            return m_root;
        }
        
        // Creates the menu items into XAML databinding
        // from the object given.
        public void CreateMenu(menuRoot jsonObject)
        {
            string otherIngredients = "";
            if (jsonObject != null)
            {
                for (int i = 0; i < jsonObject.Meals.Count; i++)
                {
                    for (int j = 1; j < jsonObject.Meals[i].menuItems.Count; j++)
                    {
                        otherIngredients += jsonObject.Meals[i].menuItems[j].name;
                    }
                    ViewModels.MainViewModel.viewMode.Items.Add(new ViewModels.ItemViewModel() { ID = Convert.ToString(i), LineOne = jsonObject.Meals[i].menuItems[0].name, LineTwo = otherIngredients });
                    otherIngredients = "";
                }
            }

        }

        // Fetches the Json string from webservice according to the parameters
        public void GetJsonData(int kitchen, int week, int day, string language)
        {
            WebClient webClient = new WebClient();
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringComplited);

            webClient.DownloadStringAsync(new System.Uri("http://www.juvenes.fi/DesktopModules/Talents.LunchMenu/LunchMenuServices.asmx/GetMenuByWeekday?KitchenId="+kitchen+"&MenuTypeId=60&Week="+week+"&Weekday="+day+"&lang="+language+"&format=json"));
        }

        // Cleans up some of the unnessasery data
        // inside the json string
        public String CleanJson(String json)
        {
            int index = json.IndexOf("\"});");
            int indexStart = json.IndexOf("{", 4);
            int length = index - indexStart;
            string substr = json.Substring(indexStart, length);
            substr = substr.Replace("\\\"" , "\"");
            return substr;
        }

        // Event handling that will be fired once the json is downloaded from webserver.
        private void webClient_DownloadStringComplited(object Sender, DownloadStringCompletedEventArgs args)
        {
            if (args.Error != null)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("Error");
                });
            }
            else
            {
               
                string str = CleanJson(args.Result);
                menuRoot buffer = Deserialize(str);
                CreateMenu(buffer);
            }
        }
    }

    
}
